import os, stat
import re
import shutil
from send2trash import send2trash

def walk_directories(directory=os.getcwd(), indent=4, indent_time=0):
    indent_time+=1
    for index, file_name in enumerate(os.listdir(directory)):
        if os.path.isdir(os.path.join(directory, file_name)):
            print("*"* indent * indent_time,file_name)
            walk_directories(os.path.join(directory, file_name), indent_time=indent_time)
        else:
            searched = re.search(r"^\d+_(.*)", file_name)
            # rename filename and save to current directory
            if searched:
                print(" "* indent * indent_time,file_name, "--->", searched.group(1))
                if os.path.exists(os.path.join(os.getcwd(), searched.group(1))):
                    send2trash(os.path.join(directory, file_name))
                    continue
                else:
                    os.rename(os.path.join(directory, file_name), os.path.join(os.getcwd(), searched.group(1)))
            # just move to current diretory
            else:
                print(" "* indent * indent_time,file_name)
                if os.path.exists(os.path.join(os.getcwd(), file_name)):
                    # send2trash(os.path.join(directory, file_name))
                    continue
                else:
                    shutil.move(os.path.join(directory, file_name), os.path.join(os.getcwd()))
    # delete empty diretory
    if not os.listdir(directory):
        os.chmod(directory, stat.S_IRWXG|stat.S_IEXEC )
        send2trash(directory)
walk_directories()